
import makeUserTempId from '@/utils/userTempId'
import { setToken, getToken, removeToken } from '@/utils/token'
import { reqUserLogin, getUserInfo, reqUserlogout } from '@/api'
const state = {
    userTempId: makeUserTempId(),
    token: getToken() || '',
    userInfo: {}
}
const mutations = {
    setToken(state, payload) {
        state.token = payload.token
        // vuex中的数据在刷新后会消失,使用local持久化存储
        setToken(payload.token)
    },
    setUserInfo(state, payload) {
        state.userInfo = payload
    },
    useLogout(state) {
        state.token = ''
        state.userInfo = {}
        removeToken()
    }
}
const actions = {
    async userLogin({ commit }, payload) {
        try {
            let re = await reqUserLogin(payload)
            commit('setToken', re)
        } catch (error) {
            return Promise.reject(error)
        }
    },
    async userInfoGet({ commit }) {
        try {
            let re = await getUserInfo()
            commit('setUserInfo', re)
        } catch (error) {
            return Promise.reject(error)
        }
    },
    async userLogout({ commit }) {
        try {
            await reqUserlogout()
            commit('useLogout')
        } catch (error) {
            return Promise.reject(error)
        }
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions

}